﻿using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Waiyun.WebApi
{
    class ConnectionPool
    {
        private static List<ConnectionNode> s_connections = new List<ConnectionNode>();
        public static OracleConnection GetConnection(string connectionString, out string errorMessage)
        {
            errorMessage = null;
            for (int index = 0; index < s_connections.Count; index++)
            {
                if (string.Equals(s_connections[index].ConnectionString, connectionString, StringComparison.CurrentCultureIgnoreCase) && s_connections[index].IsBusy == false)
                {
                    s_connections[index].IsBusy = true;
                    return s_connections[index].Connection;
                }
            }

            OracleConnection connection = new OracleConnection(connectionString);
            try
            {
                connection.Open();
                ConnectionNode node = new ConnectionNode()
                {
                    ConnectionString = connectionString,
                    Connection = connection,
                    IsBusy = true
                };
                s_connections.Add(node);
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
                connection = null;
            }
            return connection;
        }

        public static void Release(OracleConnection connection)
        {
            for (int index = 0; index < s_connections.Count; index++)
            {
                if (s_connections[index].Connection == connection)
                {
                    s_connections[index].IsBusy = false;
                    break;
                }
            }
        }
    }

    public class ConnectionNode
    {
        public string ConnectionString;
        public OracleConnection Connection;
        public bool IsBusy = false;
    }
}
